package com.quectel.pay.module.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.quectel.constant.global.SystemConstants;
import com.quectel.pay.module.merchant.service.PayChannelService;
import com.quectel.pay.module.order.dto.PayOrderDto;
import com.quectel.pay.module.order.dto.PayOrderRefundDto;
import com.quectel.pay.module.order.dto.request.InitOrderParams;
import com.quectel.pay.module.order.dto.response.NotifyCheckResult;
import com.quectel.pay.module.order.dto.response.OrderCreatedResponseDto;
import com.quectel.pay.module.order.dto.response.SendRefundResp;
import com.quectel.pay.module.order.service.OrderAliAppPayService;
import com.quectel.pay.module.order.service.OrderAliJSAPIPayService;
import com.quectel.pay.module.order.service.PayOrderService;
import com.quectel.pay.util.PayInstanceUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝APP支付
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2023-04-13 14:03:00
 */
@DubboService
public class OrderAliAppPayServiceImpl implements OrderAliAppPayService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderAliAppPayServiceImpl.class);

    @Autowired
    private PayOrderService orderService;
    @Autowired
    private PayChannelService payChannelService;
    @Autowired
    private OrderAliJSAPIPayService orderAliJSAPIPayService;

    @Override
    public OrderCreatedResponseDto createOrder(InitOrderParams initOrderParams) {
        LOGGER.info("Ali App-Pay create order params are: {}", JacksonUtils.toJsonString(initOrderParams));

        //初始化订单
        initOrderParams.setPayType(SystemConstants.PayType.ZFB.getType());
        initOrderParams.setTerminalType(SystemConstants.TerminalType.APP.getType());
        PayOrderDto orderDto = orderService.initOrderInfo(initOrderParams);


        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setSubject(orderDto.getProductName());
        model.setOutTradeNo(orderDto.getOutTradeNo());
        model.setTotalAmount(orderDto.getSpecialPrice().toPlainString());
        if (initOrderParams.getTtl() != null && initOrderParams.getTtl() > 0) {
            model.setTimeExpire(DateUtils.format(new Date(orderDto.getCreateTime().getTime() + initOrderParams.getTtl()), DateUtils.FormatType.COMMON));
        }
        request.setBizModel(model);
        request.setNotifyUrl(orderDto.getNotifyUrl());

        OrderCreatedResponseDto orderCreatedResponseDto = new OrderCreatedResponseDto();
        try {
            //调用SDK生成表单
            AlipayTradeAppPayResponse response =
                    PayInstanceUtils.getAliInstance(initOrderParams.getPayChannelId()).sdkExecute(request);
            if (response.isSuccess()) {

                orderCreatedResponseDto.setSuccess(true);
                Map<String, String> zfbMap = new HashMap<>();
                zfbMap.put("orderString", response.getBody());
                orderCreatedResponseDto.setResp(zfbMap);
                orderCreatedResponseDto.setOutTradeNo(orderDto.getOutTradeNo());

                orderDto.setRedoValue(JacksonUtils.toJsonString(orderCreatedResponseDto));
                orderService.save(orderDto);

                LOGGER.info("Ali App-Pay create order response params are: {}", JacksonUtils.toJsonString(orderCreatedResponseDto));

                return orderCreatedResponseDto;
            }

        } catch (AlipayApiException e) {
            LOGGER.error("Ali App-Pay create order failed", e);
        }
        return null;
    }

    @Override
    public SendRefundResp sendRefundRequest(Long payChannelId, PayOrderRefundDto refundReq) {
        // 支付宝各种退款使用的同一个
        return orderAliJSAPIPayService.sendRefundRequest(payChannelId, refundReq);
    }

    @Override
    public NotifyCheckResult checkNotify(Long payChannelId, Map<String, String[]> notifyParams) {
        // 支付宝各种支付的回调是用的同一个
        return orderAliJSAPIPayService.checkNotify(payChannelId, notifyParams);
    }
}
